<template>
 
    <div class="course-management">
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <h2>课程管理</h2>
        <button class="btn-primary" @click="showCreateDialog = true">
          <span>+</span> 添加课程
        </button>
      </div>

      <!-- 搜索区域 -->
      <div class="filters">
        <div class="search-box">
          <input 
            v-model="searchParams.courseName" 
            placeholder="搜索课程名称..."
            class="search-input"
            @keyup.enter="loadCourses"
          >
          <button class="btn-search" @click="loadCourses">搜索</button>
          <button class="btn-reset" @click="resetSearch">重置</button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <p>⏳ 正在加载课程数据...</p>
      </div>

      <!-- 课程列表表格 -->
      <div v-else class="table-container">
        <table v-if="courses.length > 0" class="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>课程代码</th>
              <th>课程名称</th>
              <th>学分</th>
              <th>状态</th>
              <th>创建人</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="course in courses" :key="course.id">
              <td>{{ course.id }}</td>
              <td>{{ course.courseCode }}</td>
              <td>{{ course.courseName }}</td>
              <td>{{ course.credits }}</td>
              <td>
                <span :class="['status-badge', course.status === 1 ? 'active' : 'inactive']">
                  {{ course.status === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td>{{ course.createBy || '系统' }}</td>
              <td>{{ formatDate(course.createTime) }}</td>
              <td class="action-buttons">
                <button class="btn-edit" @click="editCourse(course)">编辑</button>
                <button 
                  class="btn-toggle-status" 
                  @click="toggleCourseStatus(course)"
                  :class="course.status === 1 ? 'btn-disable' : 'btn-enable'"
                >
                  {{ course.status === 1 ? '禁用' : '启用' }}
                </button>
                <button class="btn-delete" @click="deleteCourse(course.id)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 空状态提示 -->
        <div v-else class="empty-state">
          <div class="empty-icon">📚</div>
          <p>暂无课程数据</p>
          <button class="btn-primary" @click="showCreateDialog = true">添加第一门课程</button>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="pagination.total > 0" class="pagination">
        <button :disabled="pagination.current === 1" @click="prevPage">上一页</button>
        <span>第 {{ pagination.current }} 页 / 共 {{ pagination.pages }} 页 (共 {{ pagination.total }} 条记录)</span>
        <button :disabled="pagination.current === pagination.pages" @click="nextPage">下一页</button>
      </div>

      <!-- 课程模态框 -->
      <CourseModal 
        v-if="showCreateDialog || editingCourse"
        :course="editingCourse"
        @close="closeModal"
        @saved="handleCourseSaved"
      />
    </div>
 
</template>

<script>
import { ref, onMounted } from 'vue';

import CourseModal from '@/components/CourseModal.vue';
import { courseApi } from '@/api/course';

export default {
  name: 'CourseListView',
  components: {
   
    CourseModal
  },
  setup() {
    const courses = ref([]);
    const loading = ref(false);
    const showCreateDialog = ref(false);
    const editingCourse = ref(null);
    
    const searchParams = ref({
      current: 1,
      size: 10,
      courseName: '',
      courseCode: ''
    });
    
    const pagination = ref({
      current: 1,
      size: 10,
      total: 0,
      pages: 0
    });

    const loadCourses = async () => {
      loading.value = true;
      try {
        console.log('请求参数:', searchParams.value);
        const response = await courseApi.getCourses(searchParams.value);
        console.log('完整响应:', response.data);
        
        if (response.data.code === '000000') {
          const responseData = response.data.data;
          console.log('响应数据:', responseData);
          
          // 关键修正：根据实际数据结构解析
          if (responseData && Array.isArray(responseData.data)) {
            // 数据结构：{ data: [], total: X, pageSize: X, currentPage: X }
            courses.value = responseData.data;
            pagination.value.total = responseData.total || 0;
            pagination.value.current = responseData.currentPage || 1;
            pagination.value.pages = Math.ceil(pagination.value.total / searchParams.value.size);
          } else if (Array.isArray(responseData)) {
            // 如果返回的是直接数组
            courses.value = responseData;
            pagination.value.total = responseData.length;
            pagination.value.pages = 1;
          } else {
            console.error('无法解析的数据结构:', responseData);
            courses.value = [];
          }
          
          console.log('解析后的课程数据:', courses.value);
          console.log('课程数量:', courses.value.length);
        } else {
          console.error('接口返回错误:', response.data.msg);
          courses.value = [];
        }
      } catch (error) {
        console.error('加载课程列表失败:', error);
        courses.value = [];
      } finally {
        loading.value = false;
      }
    };

    const editCourse = (course) => {
      editingCourse.value = { ...course };
    };

    const deleteCourse = async (id) => {
      if (confirm('确定要删除这门课程吗？此操作不可恢复。')) {
        try {
          await courseApi.deleteCourse(id);
          await loadCourses();
        } catch (error) {
          console.error('删除失败:', error);
          alert('删除失败: ' + (error.response?.data?.message || error.message));
        }
      }
    };

    const toggleCourseStatus = async (course) => {
      const newStatus = course.status === 1 ? 0 : 1;
      try {
        await courseApi.updateCourseStatus(course.id, newStatus);
        await loadCourses();
      } catch (error) {
        console.error('更新课程状态失败:', error);
        alert('操作失败: ' + (error.response?.data?.message || error.message));
      }
    };

    const resetSearch = () => {
      searchParams.value.courseName = '';
      searchParams.value.courseCode = '';
      searchParams.value.current = 1;
      loadCourses();
    };

    const closeModal = () => {
      showCreateDialog.value = false;
      editingCourse.value = null;
    };

    const handleCourseSaved = () => {
      closeModal();
      loadCourses();
    };

    const prevPage = () => {
      if (searchParams.value.current > 1) {
        searchParams.value.current--;
        loadCourses();
      }
    };

    const nextPage = () => {
      if (searchParams.value.current < pagination.value.pages) {
        searchParams.value.current++;
        loadCourses();
      }
    };

    const formatDate = (dateString) => {
      if (!dateString) return '-';
      try {
        return new Date(dateString).toLocaleDateString();
      } catch (error) {
        return dateString;
      }
    };

    onMounted(() => {
      loadCourses();
    });

    return {
      courses,
      loading,
      searchParams,
      pagination,
      showCreateDialog,
      editingCourse,
      loadCourses,
      editCourse,
      deleteCourse,
      toggleCourseStatus,
      resetSearch,
      closeModal,
      handleCourseSaved,
      prevPage,
      nextPage,
      formatDate
    };
  }
};
</script>

<style scoped>
.course-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filters {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 200px;
}

.btn-primary, .btn-search, .btn-reset {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-search {
  background-color: #2ecc71;
  color: white;
}

.btn-reset {
  background-color: #95a5a6;
  color: white;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-badge.inactive {
  background: #ffebee;
  color: #d32f2f;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.btn-edit, .btn-delete, .btn-toggle-status {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-edit {
  background-color: #ff9800;
  color: white;
}

.btn-delete {
  background-color: #f44336;
  color: white;
}

.btn-enable {
  background-color: #4caf50;
  color: white;
}

.btn-disable {
  background-color: #9e9e9e;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>